package com.study.demo.security;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.social.security.SocialUser;
import org.springframework.social.security.SocialUserDetails;
import org.springframework.social.security.SocialUserDetailsService;
import org.springframework.stereotype.Component;

/**
 * @author LiYongKui
 * @version 1.0
 * @date 2021/3/31 12:52
 */
@Component
public class CustomUserDetailService implements UserDetailsService, SocialUserDetailsService {

    Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 密码加密注册时使用
     */
    @Autowired
    private PasswordEncoder passwordEncoder;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        logger.info("===》  表单登陆用户名：{}", username);
        return buildUser(username);
    }

    @Override
    public SocialUserDetails loadUserByUserId(String userId) throws UsernameNotFoundException {
        logger.info("===》  社交登陆用户名：{}", userId);
        return buildUser(userId);
    }

    private SocialUser buildUser(String userId) {
        /**
         *  boolean enabled 是否可用,
         *  boolean accountNonExpired 是否没过期,
         *  boolean credentialsNonExpired 密码是否失效,
         *  boolean accountNonLocked 是否锁定
         */
        return new SocialUser(userId, passwordEncoder.encode("123456"),
                AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
    }
}
